### SECTION 1 PRODUCE THE REGRESSION MODELS, TABLES AND FIGURES USED IN THE ARTICLE. 
### SECTION 2 PROCUDE THE DESCRIPTIVE STATISTICS IN THE ARTICLE
### SEE REPLICATION SCRIPT APPENDIX FOR ALL CONTROL MODELS

# get packages ------------------------------------------------------------
pkgs <- c("tidyverse", "lubridate", "margins", "stargazer", "ggrepel",
          "xtable", "kableExtra", "texreg", "readxl") 
for (pkg in pkgs) library(pkg, character.only = TRUE)

# load data ----------------------------------------------------------------
case <- read_excel("case_data.xlsx")
vote <- read_excel("indivdual_data.xlsx")

# make docket type factor variable
case$docket_type <- as.factor(case$docket_type)
levels(case$docket_type) <- list(
  Mandatory = "mandatory",
  Mandatory_principled = "mandatory principled",
  External_board = "external appeals board",
  Docket_control = "docket control"
)

# SECTION 1 ---------------------------------------------------------------

# We create a new dataframe without the external appeals board commitee
# There are no dissent cases in the external appeals board commitee
# This reduced dataset is used for the non-unanimity model and dissent model
case_reduced <- case %>% 
  filter(external_appeals_board==0)

# we drop external appeals board level from factor variable
#table(case_reduced$docket_type)
case_reduced$docket_type <- droplevels(case_reduced)$docket_type
#table(case_reduced$docket_type)

# NON-UNANIMITY
# Model 1 table 3 in article. Controlling for panel size (this model corresponds to model n3 in the appendix)
m_nonunanimous <- glm(nonunanimous ~ docket_type + seven_nine_justice_panels,
          data = case_reduced,
          family = binomial('logit'))

# DISSENT
# model 2 table 3 in the article. controlling for panel size (this model corresponds to model d3 in the appendix)
m_dissent <- glm(dissent_no_concurrence ~ docket_type
          + seven_nine_justice_panels,
          data = case_reduced, 
          family = binomial('logit'))

# REVERSAL
# model 3 table 3 in the article (this model corresponds to model # in the appendix)
m_reversal <- glm(reversal ~ docket_type
          + seven_nine_justice_panels
          + eu
          + echr
          + government_appellant
          + individuals, 
          data = case, 
          family = binomial('logit'))

# Generate figure 2 in the manuscript nonunanimous, dissent & reversal -------------------------------------------------

# predicted probabilities for non-unanimous decisions
ame_nonunanimous <- summary(margins(m_nonunanimous)) %>%
  mutate(labels = ifelse(factor == "docket_typeDocket_control",
                         "Discretionary", "Mandatory principled"), # generate labels for figure 
         model = "Nonunanimous") %>% # generate model name
  filter(factor!= "seven_nine_justice_panels") # keep only estimates for docket type variables

# predicted probabilities for dissent decisions
ame_dissent <- summary(margins(m_dissent)) %>%
  mutate(labels = ifelse(factor == "docket_typeDocket_control",
                         "Discretionary", "Mandatory principled"), # generate labels for figure
         model = "Dissent") %>% # generate model name
  filter(labels == "Discretionary") # keep only estimates for discretionary docket 

# predicted probabilities for reversal decisions
ame_reversal <- summary(margins(m_reversal)) %>%
  mutate(labels = ifelse(factor=="docket_typeDocket_control",
                         "Discretionary",
                         ifelse(factor=="docket_typeExternal_board",
                                "External appeals board", "Mandatory principled")), # generate labels for figure
         model = "Reversal") %>% 
  filter(str_detect(factor, "^doc")) # keep only estimates for docket 

# nonunanimous, dissent, reversal margins in one dataframe for construction of figure 2
ame_fig2 <- rbind(ame_nonunanimous, ame_dissent, ame_reversal) %>% 
  mutate(model2 = ifelse(model == "Reversal", "Reversal", "Nonunanimous"),
         model3 = ifelse(model == "Dissent", "Dissent", "no"))


# figure 2 in the article
f2 <- ggplot(ame_fig2, aes(labels, AME, color = model3)) +
  geom_hline(yintercept=0, lty=2, lwd=1, colour="grey") +
  geom_linerange(aes(ymin = lower,
                     ymax = upper),
                 lwd = 1, position = position_dodge(width = 0.6)) +
  geom_text(size=4, aes(label = round(AME, digits=2)),
            data = filter(ame_fig2, model == "Dissent"),
            fontface = 'bold', color = 'black',
            nudge_x = 0.01
  ) +
  geom_text(size=4, aes(label = round(AME, digits=2)),
            data = filter(ame_fig2, model == "Nonunanimous" & labels == "Mandatory principled"),
            fontface = 'bold', color = 'black',
            nudge_x = 0.15
  ) +
  geom_text(size=4, aes(label = round(AME, digits=2)),
            data = filter(ame_fig2, model == "Nonunanimous" & labels == "Discretionary"),
            fontface = 'bold', color = 'black', nudge_x = 0.3) +
  geom_text(size=4, aes(label = round(AME, digits=2)),
            data = filter(ame_fig2, model == "Reversal"),
            fontface = 'bold', color = 'black',
            nudge_x = 0.2
  ) +
  scale_color_manual(values = c( "grey", "black")) +
  labs(x ="") +
  geom_point(size = 3, position = position_dodge(width = 0.6)) +
  facet_wrap(model2 ~., scales = "free") +
  scale_y_continuous(limits = c(-0.3, 0.4)) +
  theme_minimal() +
  labs(x ="Average change in predicted probability\n compared to mandatory jurisdiction",
       y = "") +
  theme(text = element_text(size = 12, face = "italic"),
        legend.position = "none")

# make tiff file for article
ggsave("f2.tiff", plot = f2,  compression = "lzw", height=6, width=10, units="in", dpi=300)

# EFFECTS OF DOCKET TYPE ON THE SUCCESS OF INDIVIDUAL PRIVATE LITIGANTS 
# use case_reduced data because of very few observations on external appeal board

# model 4 in table 3 in the article (this model corresponds to model # in the appendix)
m_governmentwin <- glm(government_win ~ docket_type
          + individuals
          + docket_type:individuals
          + government_appellant,
          data = case_reduced, 
          family = binomial('logit'))

# Generate figure 3 in the aticle  -------------------------------------------------
# predicted probabilities docket type*individuals  
ame_parties <- cplot(m_governmentwin, x = "docket_type", dx = "individuals", 
                         what = "effect", type = "response", draw = FALSE) %>% 
  mutate(name = c("Mandatory", "Mandatory principled", "Discretionary"),
         Individuals = "Individuals") # labels for figure 3

# figure 3 in the article
f3 <- ggplot(ame_parties, aes(Individuals, yvals)) +
  geom_hline(yintercept = 0, lty = 2, lwd = 1, colour = "grey") +
  geom_errorbar(aes(ymin = lower, ymax = upper),
                lwd = 1, width = 0, position = position_dodge(width = 0.5)) +
  geom_text(size = 4, aes(label = round(yvals, digits = 2)), 
            fontface = 'bold', color = 'black', nudge_x = 0.2) +
  labs(x ="Average change in predicted probability\n of government win compared to Corporations/Associations",
       y = "") +
  geom_point(size=3, position = position_dodge(width = 0.5)) +
  facet_wrap(name ~. ) +
  scale_y_continuous(limits = c(-0.3, 0.4)) +
  theme_minimal() +
  theme(text = element_text(size = 12, face = "italic"))

# make tiff file for article
ggsave("f3.tiff", plot = f3,  compression = "lzw", height = 6, width = 10, units = "in", dpi = 300)


# this code is used by author to generate table 3 in the article
stargazer(m_nonunanimous, m_dissent, m_reversal, m_governmentwin,
           digits = 2,
           header = F,
           style = "ajps",
           dep.var.labels= c("Non-unanimity", "Dissent", "Reversal", "Government win"),
           title = "Table 3: Logistic regression models: nonunanimous decision, dissent, reversal and government win",
          align = T, 
          covariate.labels = c("Docket type: mandatory principled",
                                "Docket type: external appeals board",
                                "Docket type: discretionary",
                                "Docket type: mandatory principled * individuals",
                                "Docket type: discretionary * individuals",
                                "Individuals"),
          omit = c("seven_nine_justice_panels", "eu", "echr", "government_appellant"),
           type = "html",
           omit.stat = "ll",
            notes =  "Coefficients are logits. Standard errors in parentheses. Model 1 and model 2 controls for enlarged panels, model 3 controls for enlarged panels, eu, echr, government appellant and individuals, model 4 controls for government appellant, but not displayed here. The full results are displayed in table A1-A4 in the Appendix.", 
           out = "main_models_article.doc")

# EFFECTS OF DOCKET TYPE ON ATTITUDINAL BEHAVIOR 
# subset data to nonunanimous decisions
nonunanimous <- as.data.frame(vote) %>% 
  filter(nonunanimous == 1) %>% 
  filter(!is.na(government_vote)) # we drop one case in the norwegian data with missing data on government vote because of unclear win

# subset data to discretionary docket
nonunanimous_norway <- nonunanimous %>% 
  filter(docket_type == "Docket_control") %>% 
  mutate(independent_appointment = ifelse(appointment_year > 2002, 1, 0)) # independent appointment variable

# subset data to mandatory dockets 
nonunanimous_denmark <-  nonunanimous %>% 
  filter(docket_type != "Docket_control")

# Discretionary docket model
# model 5 table 4 in article (this model corresponds to model # in the appendix)
m_gvote_norway <- glm(government_vote ~ j.government
                 + individuals
                 + government_appellant, 
                 data = nonunanimous_norway,
                 family = binomial("logit"))


# Mandatory docket model 
# model 6 table 4 in article (this model corresponds to model # in the appendix)
m_gvote_denmark <- glm(government_vote ~ j.government
                  + docket_type
                  + docket_type:j.government
                  + seniority
                  + gender
                  + centre_born
                  + j.academic, 
                  data = nonunanimous_denmark,
                  family = binomial("logit"))


# Generate figure 4 in the article ----------------------------------------
# predicted probabilities attitudinal discretionary docket 
ame_gvote_norway <- summary(margins(m_gvote_norway, type = "response"),
                         data = nonunanimous_norway) %>% 
  mutate(name = "Discretionary",
         Executive = "Government career") %>% 
  filter(factor == "j.government") %>% 
  select(AME, upper, lower, name, Executive)


# predicted probabilities attitudinal mandatory dockets
ame_gvote_denmark<-cplot(m_gvote_denmark, x = "docket_type", dx = "j.government",
                      what = "effect", type = "response",
                      data = nonunanimous_denmark,
                      draw = FALSE) %>%
  mutate(name = c("Mandatory", "Mandatory principled"),
         Executive = "Government career",
         AME = yvals) %>% 
  filter(factor=="j.government") %>% 
  select(AME, upper, lower, name, Executive)

# make one dataframe for figure
ame_fig4 <- rbind(ame_gvote_norway, ame_gvote_denmark)

# generate figure H4
f4 <- ggplot(ame_fig4, aes(Executive, AME)) +
  geom_hline(yintercept=0, lty=2, lwd=1, colour="grey") +
  geom_errorbar(aes(ymin=lower, ymax=upper),
                lwd=1, width=0, position = position_dodge(width = 0.5)) +
  geom_text(size=4,aes(label= round(AME, digits=3)),
            fontface = 'bold', color = 'black', nudge_x = 0.2) +
  labs(x ="Average change in predicted probability\n of government vote",
       y = "") +
  geom_point(size=3, position = position_dodge(width = 0.5)) +
  facet_wrap(name ~. ) +
  scale_y_continuous(limits = c(-0.3, 0.5)) +
  theme_minimal() +
  theme(text = element_text(size=14, face = "italic"))

# make tiff file for article
ggsave("f4.tiff", plot = f4,  compression = "lzw", height=6, width=10, units="in", dpi=300)


# generate table 4 in the article (we edited model names from model  1 and 2 to model 5 and 6 afterwards)
stargazer(m_gvote_norway, m_gvote_denmark,
          digits = 2, 
          header = F,
          style = "ajps",
          #dep.var.labels = c("Government vote discretionary docket", "Government vote mandatory docket"),
          title = "Table 4: Logistic regression models: government vote",
          covariate.labels = c("Government career",
                               "Docket type: mandatory principled",
                               "Docket type: mandatory principled * government career"),
          omit = c("individuals", "government_appellant", "seniority", "gender", "centre_born", "j.academic"),
type = "html",
omit.stat = "ll",
notes =  "Coefficients are logits. Standard errors in parentheses. Model 4 controls for individuals and government appellant, model 5 controls for seniority, gender, centre born, academic, but not displayed here. The full results are displayed in table A5-A6 in the Appendix.",
out = "main_models2_article.doc")


# SECTION 2 ---------------------------------------------------------------
# generate table 2 Descriptive statistics for dependent (DV) and independent (IV) variables descriptive stat tables
# dependent variables
nonunanimous_d <- c(N = length(which(!is.na(case$nonunanimous))),
                    Mean = as.numeric(mean(case$nonunanimous)), 
                    Sd = as.numeric(sd(case$nonunanimous)), 
                    Min = as.numeric(min(case$nonunanimous)), 
                    Max = as.numeric(max(case$nonunanimous)))

dissent <- c(N=length(which(!is.na(case$dissent_no_concurrence))),
             Mean = as.numeric(mean(case$dissent_no_concurrence)), 
             Sd = as.numeric(sd(case$dissent_no_concurrence)), 
             Min = as.numeric(min(case$dissent_no_concurrence)), 
             Max = as.numeric(max(case$dissent_no_concurrence)))

reversal <- c(length(which(!is.na(case$reversal))),
              Mean = as.numeric(mean(case$reversal, na.rm=T)), 
              Sd = as.numeric(sd(case$reversal, na.rm=T)), 
              Min = as.numeric(min(case$reversal, na.rm=T)), 
              Max = as.numeric(max(case$reversal, na.rm=T)))

government_win <- c(N=length(which(!is.na(case$government_win))),
                    Mean=as.numeric(mean(case$government_win, na.rm=T)),
                    Sd = as.numeric(sd(case$government_win, na.rm=T)), 
                    Min = as.numeric(min(case$government_win, na.rm=T)), 
                    Max = as.numeric(max(case$government_win, na.rm=T)))

government_vote <- c(N=length(which(!is.na(nonunanimous$government_vote))),
                     Mean = as.numeric(mean(nonunanimous$government_vote, na.rm=T)), 
                     Sd = as.numeric(sd(nonunanimous$government_vote, na.rm=T)), 
                     Min = as.numeric(min(nonunanimous$government_vote, na.rm=T)), 
                     Max = as.numeric(max(nonunanimous$government_vote, na.rm=T)))

dep_vars <- rbind(nonunanimous_d, dissent, reversal, government_win, government_vote)

dep_vars<-as.data.frame(dep_vars) %>% 
   mutate(Variable = c("Nonunanimous", "Dissent", "Reversal", "Government win", "Government vote"),
          Type = "DV") %>% 
   select(Variable, Type, N, Mean, Sd, Min, Max)


# independent variables
docketcontrol <- c(
  N = length(which(!is.na(case$docket_control2))),
  Mean = as.numeric(mean(case$docket_control2)),
  Sd = as.numeric(sd(case$docket_control2)),
  Min = as.numeric(min(case$docket_control2)),
  Max = as.numeric(max(case$docket_control2))
)

mandatory <- c(
  N = length(which(!is.na(case$mandatory))),
  Mean = as.numeric(mean(case$mandatory)),
  Sd = as.numeric(sd(case$mandatory)),
  Min = as.numeric(min(case$mandatory)),
  Max = as.numeric(max(case$mandatory))
)

mandatory_principled <-
  c(
    N = length(which(!is.na(
      case$mandatory_principled
    ))),
    Mean = as.numeric(mean(case$mandatory_principled)),
    Sd = as.numeric(sd(case$mandatory_principled)),
    Min = as.numeric(min(case$mandatory_principled)),
    Max = as.numeric(max(case$mandatory_principled))
  )

external_appeals_board <-
  c(
    N = length(which(!is.na(
      case$external_appeals_board
    ))),
    Mean = as.numeric(mean(case$external_appeals_board)),
    Sd = as.numeric(sd(case$external_appeals_board)),
    Min = as.numeric(min(case$external_appeals_board)),
    Max = as.numeric(max(case$external_appeals_board))
  )

individuals <- c(
  N = length(which(!is.na(case$individuals))),
  Mean = as.numeric(mean(case$individuals, na.rm = T)),
  Sd = as.numeric(sd(case$individuals, na.rm = T)),
  Min = as.numeric(min(case$individuals,  na.rm = T)),
  Max = as.numeric(max(case$individuals,  na.rm = T))
)

government_career <- c(N=length(which(!is.na(nonunanimous$j.government))),
                       Mean = as.numeric(mean(nonunanimous$j.government,  na.rm=T)), 
                       Sd = as.numeric(sd(nonunanimous$j.government,  na.rm=T)), 
                       Min = as.numeric(min(nonunanimous$j.government,  na.rm=T)), 
                       Max = as.numeric(max(nonunanimous$j.government,  na.rm=T)))

indep_vars <- rbind(docketcontrol, mandatory, mandatory_principled, external_appeals_board, 
                    individuals, government_career)

indep_vars <- as.data.frame(indep_vars) %>% 
  mutate(Variable = c("Docket type: docket control", 
                      "Docket type: mandatory", 
                      "Docket type: mandatory principled",
                      "Docket type: external appeals board",
                      "Individuals",
                      "Government career"),
         Type = "IV") %>% 
  select(Variable, Type, N, Mean, Sd, Min, Max)


variables <- rbind(dep_vars, indep_vars)

stargazer(variables, 
          digits = 2, 
          header = F,
          rownames = F,
          summary = F,
          title = "Table 2: Descriptive statistics for dependent (DV) and independent (IV) variables",
          type = "html",
          out = "descriptive_stat.doc")